#!/bin/bash

# Playwright依赖安装脚本
# 用于在Linux系统上安装Playwright所需的系统依赖

set -e

# 设置字符编码
export LC_ALL=C.UTF-8
export LANG=C.UTF-8

echo "🎭 Playwright依赖安装工具"
echo "=========================="

# 添加错误处理函数
handle_error() {
    echo "❌ 安装过程中出现错误，请检查上面的错误信息"
    echo "💡 常见解决方案："
    echo "   1. 检查网络连接"
    echo "   2. 更新软件包管理器缓存"
    echo "   3. 检查系统权限"
    echo "   4. 手动运行: playwright install-deps"
    exit 1
}

# 设置错误处理
trap 'handle_error' ERR

# 检测操作系统
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo "✅ 检测到Linux系统"
    
    # 检测发行版
    if [ -f /etc/debian_version ]; then
        DISTRO="debian"
        echo "📦 检测到Debian/Ubuntu系统"
    elif [ -f /etc/redhat-release ]; then
        DISTRO="redhat"
        echo "📦 检测到RedHat/CentOS系统"
    elif [ -f /etc/arch-release ]; then
        DISTRO="arch"
        echo "📦 检测到Arch Linux系统"
    else
        echo "⚠️  未知的Linux发行版，尝试使用通用方法"
        DISTRO="unknown"
    fi
else
    echo "❌ 此脚本仅支持Linux系统"
    exit 1
fi

# 检查是否为root用户或有sudo权限
if [ "$EUID" -eq 0 ]; then
    SUDO=""
    echo "🔑 以root用户运行"
elif command -v sudo &> /dev/null; then
    SUDO="sudo"
    echo "🔑 使用sudo权限"
else
    echo "❌ 需要root权限或sudo权限来安装系统依赖"
    exit 1
fi

# 安装Python和pip（如果需要）
echo "🐍 检查Python环境..."
if ! command -v python3 &> /dev/null; then
    echo "安装Python3..."
    if [ "$DISTRO" = "debian" ]; then
        $SUDO apt-get update
        $SUDO apt-get install -y python3 python3-pip
    elif [ "$DISTRO" = "redhat" ]; then
        $SUDO yum install -y python3 python3-pip
    elif [ "$DISTRO" = "arch" ]; then
        $SUDO pacman -S python python-pip
    fi
else
    echo "✅ Python3已安装"
fi

# 安装Playwright Python包（如果需要）
echo "🎭 检查Playwright Python包..."
if ! python3 -c "import playwright" 2>/dev/null; then
    echo "安装Playwright Python包..."
    python3 -m pip install --upgrade pip
    python3 -m pip install playwright
else
    echo "✅ Playwright Python包已安装"
fi

# 安装系统依赖
echo "📦 安装系统依赖..."

if [ "$DISTRO" = "debian" ]; then
    echo "使用apt安装依赖..."
    $SUDO apt-get update
    $SUDO apt-get install -y \
        libnss3 \
        libnspr4 \
        libatk-bridge2.0-0 \
        libdrm2 \
        libxkbcommon0 \
        libxcomposite1 \
        libxdamage1 \
        libxrandr2 \
        libgbm1 \
        libxss1 \
        libasound2 \
        libatspi2.0-0 \
        libgtk-3-0 \
        libgdk-pixbuf2.0-0 \
        libxcursor1 \
        libxi6 \
        libxrender1 \
        libxext6 \
        libx11-6 \
        libxft2 \
        libxinerama1 \
        libxtst6 \
        libappindicator3-1 \
        libx11-xcb1 \
        libxfixes3 \
        xdg-utils \
        fonts-liberation \
        fonts-dejavu-core

elif [ "$DISTRO" = "redhat" ]; then
    echo "使用yum/dnf安装依赖..."
    # 检测是否使用dnf
    if command -v dnf &> /dev/null; then
        PKG_MGR="dnf"
    else
        PKG_MGR="yum"
    fi
    
    # 先尝试解决可能的包冲突
    echo "解决包冲突..."
    $SUDO $PKG_MGR clean packages
    
    # 分批安装，避免冲突，使用--skip-broken跳过有问题的包
    echo "安装基础依赖..."
    $SUDO $PKG_MGR install -y --skip-broken \
        at-spi2-atk \
        libdrm \
        libxkbcommon \
        libXcomposite \
        libXdamage \
        libXrandr \
        mesa-libgbm \
        libXScrnSaver \
        alsa-lib \
        at-spi2-core \
        gtk3 \
        gdk-pixbuf2 \
        libXcursor \
        libXi \
        libXrender \
        libXext \
        libX11 \
        libXft \
        libXinerama \
        libXtst \
        libX11-xcb \
        libXfixes \
        xdg-utils
    
    echo "安装字体..."
    $SUDO $PKG_MGR install -y --skip-broken \
        liberation-fonts \
        dejavu-sans-fonts
    
    # NSS相关包单独处理，避免版本冲突
    echo "检查NSS包..."
    if ! rpm -q nss >/dev/null 2>&1; then
        echo "安装NSS..."
        $SUDO $PKG_MGR install -y nss nspr
    else
        echo "NSS已安装，跳过"
    fi

elif [ "$DISTRO" = "arch" ]; then
    echo "使用pacman安装依赖..."
    $SUDO pacman -S --noconfirm \
        nss \
        nspr \
        at-spi2-atk \
        libdrm \
        libxkbcommon \
        libxcomposite \
        libxdamage \
        libxrandr \
        mesa \
        libxss \
        alsa-lib \
        at-spi2-core \
        gtk3 \
        gdk-pixbuf2 \
        libxcursor \
        libxi \
        libxrender \
        libxext \
        libx11 \
        libxft \
        libxinerama \
        libxtst \
        libx11-xcb \
        libxfixes \
        xdg-utils \
        ttf-liberation \
        ttf-dejavu

else
    echo "⚠️  未知发行版，请手动安装Playwright依赖"
    echo "可以尝试运行: playwright install-deps"
fi

# 安装Playwright浏览器
echo "🌐 安装Playwright浏览器..."
python3 -m playwright install chromium

# 验证安装
echo "✅ 验证安装..."
if python3 -c "
from playwright.sync_api import sync_playwright
try:
    with sync_playwright() as p:
        browser = p.chromium.launch()
        browser.close()
    print('✅ Playwright安装成功！')
except Exception as e:
    print(f'❌ Playwright验证失败: {e}')
    exit(1)
"; then
    echo ""
    echo "🎉 Playwright依赖安装完成！"
    echo "现在可以正常使用闲鱼自动回复系统了"
else
    echo ""
    echo "❌ 安装验证失败，请检查错误信息"
    exit 1
fi 